package com.site.action.backend.system;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.site.dto.backend.system.AuthorityBizBean;
import com.site.dto.backend.system.ResourseBizBean;
import com.site.dto.backend.system.RoleBizBean;
import com.site.dto.backend.system.UsersBizBean;
import com.site.service.backend.system.AuthService;
import com.site.service.backend.system.RoleService;
import com.site.service.backend.system.UsersService;
import com.site.util.StringUtils;
import com.site.util.base.action.BackendBaseAction;
import com.site.util.base.service.BaseService;
import com.site.util.exception.ApplicationException;

/**
 * 角色Action
 * 
 * @author Lee 2012-12-04
 * 
 */
public class RoleAction extends BackendBaseAction {

	private static final long serialVersionUID = 1L;

	private RoleBizBean roleBizBean;

	private List<RoleBizBean> roleBizBeanList;

	private List<UsersBizBean> usersBizBeanList;
	/*
	 * 资源
	 */
	private List<ResourseBizBean> resourseBizBeanList;
	/*
	 * 权限
	 */
	private List<AuthorityBizBean> authList;
	
	private Long roleId;
	/*
	 * 用于前台Extjs传递角色id参数 
	 */
	private String role;
	
	private UsersBizBean usersBizBean;
	
	private AuthorityBizBean authorityBizBean;
	/*
	 * 角色ids
	 */
	private String ids;
	/*
	 * 角色Service
	 */
	private RoleService roleService;
	/*
	 * 用户Service
	 */
	private UsersService usersService;
	
	/*
	 *权限Service 
	 */
	private AuthService  authService;
	/*
	 * 旧角色名
	 */
	private String oldroleName;
	/*
	 * 锁定，解锁 id 字符串
	 * 格式：123,123,1233
	 */
	private String idsStr;
	
	public RoleBizBean getRoleBizBean() {
		return roleBizBean;
	}
	
	public void setRoleBizBean(RoleBizBean roleBizBean) {
		this.roleBizBean = roleBizBean;
	}
	
	public List<RoleBizBean> getRoleBizBeanList() {
		return roleBizBeanList;
	}

	public void setRoleBizBeanList(List<RoleBizBean> roleBizBeanList) {
		this.roleBizBeanList = roleBizBeanList;
	}

	@Resource
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	
	public RoleService getRoleService() {
		return roleService;
	}
	
	/**
	 * 获得角色列表
	 * 
	 * @return
	 */
	public String getRoleList() {
		if (queryPage == null) {
			initPagination();
		}
		roleBizBeanList = roleService.getRoleList(queryPage, roleBizBean);
		return "getRoleList";
	}

	/**
	 * 保存角色
	 * 
	 * @return
	 */
	public String save() throws ApplicationException,Exception {
		try {
			if (roleBizBean.getRoleName() == null || "".equals(roleBizBean.getRoleName().trim())) {
				response.getWriter().print("{\"msg\":\"角色名称不能为空!\"}");
				log.info("验证角色失败,角色名称不能为空……");
			} else if (!roleBizBean.getRoleName().equals(oldroleName) && roleService.getRoleByName(roleBizBean.getRoleName()) != null){
				response.getWriter().print("{\"msg\":\"角色已存在……\"}");
				log.info("验证角色失败,角色已存在……");
			} else if (getCurrentUser() != null) {
				roleBizBean.setCreatedUser(getCurrentUser().getUserName());
				roleBizBean.setUpdatedUser(getCurrentUser().getUserName());
				roleService.execute(roleBizBean, BaseService.COMMAND_SAVE);
				response.getWriter().print("{\"msg\":\"\"}");
				log.info("角色增加……");
			}
		} catch (ApplicationException e) {
			throw (e);
		}
		return null;
	}

	/**
	 * 更新角色
	 * 
	 * @return
	 */
	public String update()throws ApplicationException, Exception  {
		try {
			if(null != roleBizBean && roleBizBean.getId() !=null){
				roleService.execute(roleBizBean, BaseService.COMMAND_UPDATE);
				response.getWriter().print("{\"msg\":\"\"}");
				log.info("角色更新成功……");
			} else {
				response.getWriter().print("{\"msg\":\"角色Id为空!\"}");
				log.info("角色id不能为空……");
			}
		} catch (ApplicationException e) {
			throw (e);
		}
		return null;
	}
	/**
	 * 更新角色页面
	 * @return
	 */
	public String updatePage()throws Exception{
		if (queryPage == null) {
			initPagination();
		}
		
		if(null != roleBizBean  && roleBizBean.getId() != null){
			roleBizBeanList = roleService.getRoleList(queryPage, roleBizBean);
			if(null != roleBizBeanList && roleBizBeanList.size() == 1){
				log.info(JSONObject.toJSONString(roleBizBeanList.get(0)));
				response.getWriter().print(JSONObject.toJSONString(roleBizBeanList.get(0)));
			}
			log.info("角色获得成功，正在返回……");
		} else {
			response.getWriter().print("{\"msg\":\"\"}");
			log.info("角色id获得失败……");	
		}
		return null;
	}
	
	
	/**
	 * 物理删除角色
	 * @return
	 */
	public String roleDelete(){
		
		try {
    		
    		if(null != roleBizBeanList && roleBizBeanList.size() > 0) {
        		String name = (String)roleService.execute(roleBizBeanList, BaseService.COMMAND_DELETE);
        		super.setParams(name);
        		super.setMessageID("SYS_MSG_00022");
        	} else {
        		log.info("编号为空。。。。。");
				super.setMessageID("SYS_MSG_00026");
        	}
    		
    	} catch(Exception e) {
    		super.setMessageID("SYS_MSG_00026");
    		e.printStackTrace();
    	}
    	
    	super.setBackurl(request.getContextPath() + "/system/roleAction!getRoleList.do");
		return "toMessage";
	}
	
	
	
	
	/**
	 * 删除角色(逻辑删除即禁用)
	 * @return
	 */
	public String disabled()throws Exception{
		try {
			if(null != idsStr && idsStr.length() > 0){
				roleService.execute(idsStr, "disabled");
				log.info("逻辑删除(禁用)成功!");
				response.getWriter().print("{\"message\":\"禁用成功!\"}");
			} else {
				log.info("逻辑删除(禁用)失败,角色id为空!");
			}
		} catch (ApplicationException e) {
			throw (e);
		}
		return null;
	}
	
	/**
	 * 启用角色(启用)
	 * @return
	 */
	public String enabled()throws Exception{
		try {
			if(null != idsStr && idsStr.length() > 0){
				roleService.execute(idsStr, "enabled");
				log.info("启用成功!");
				response.getWriter().print("{\"message\":\"启用成功!\"}");
			} else {
				log.info("启用失败！角色id为空！");
			}
		} catch (ApplicationException e) {
			throw (e);
		}
		return null;
	}
	
	/**
	 * 根据角色id获得角色下的所有用户
	 * @return
	 */
	public String getRoleUsers(){
		if(null != roleId){
			usersBizBeanList = roleService.getRoleUsers(roleId);
		}
		roleBizBeanList = roleService.getRoleList(null, null);
		return "getRoleUsers";
	}

	/**
	 * 查询非该角色用户
	 * @return
	 */
	public String getNotRoleUser(){
		if(queryPage == null) {
			initPagination();
		}
		usersBizBeanList = usersService.getNotRoleUserList(roleId, usersBizBean, queryPage);
		return "chooseUser";
	}
	
	/**
	 * 增加角色用户
	 * @return
	 */
	public String saveRoleUser(){
		
		if(null != roleBizBean && !StringUtils.isEmpty(roleBizBean.getUserIds())){
			roleBizBean.setId(roleId);
			roleService.execute(roleBizBean, "saveRoleUser");
		}
		return "roleUserSuccess";
	}
	/**
	 * 删除角色用户
	 * @return
	 */
	public String deleteRoleUser(){
		
		if(null != roleBizBean && !StringUtils.isEmpty(roleBizBean.getUserIds())){
			roleBizBean.setId(roleId);
			roleService.execute(roleBizBean, "deleteRoleUser");
		}
		return "roleUserSuccess";
	}
	/**
	 * 查询角色和权限关联
	 * 
	 * @return
	 */
	public String getRoleAuth() {
		try {
			if (this.roleId != null) {
				Map<String, List<AuthorityBizBean>> temp_Map = roleService.getRoleAuth(roleId);
				authList = temp_Map.get("auth_y");
			} else {
				authList = authService.getAuthList(null,null);
			}
			roleBizBeanList = roleService.getRoleList(null, null);
		} catch (Exception e) {
			log.info(e.getMessage());
		}
		return "roleAuthList";
	}
	/**
	 * 查询非该角色权限
	 * @return
	 */
	public String getNotRoleAuth(){
		if(queryPage == null) {
			initPagination();
		}
		authList = authService.getNotRoleAuth(roleId, authorityBizBean, queryPage);
		return "chooseAuth";
	}
	
	/**
	 * 增加角色权限
	 * @return
	 */
	public String saveRoleAuth(){
		
		if(null != roleBizBean && !StringUtils.isEmpty(roleBizBean.getAuthIds())){
			roleBizBean.setId(roleId);
			roleService.execute(roleBizBean, "saveRoleAuth");
		}
		return "roleAuthSuccess";
	}
	/**
	 * 删除角色权限
	 * @return
	 */
	public String deleteRoleAuth(){
		
		if(null != roleBizBean && !StringUtils.isEmpty(roleBizBean.getAuthIds())){
			roleBizBean.setId(roleId);
			roleService.execute(roleBizBean, "deleteRoleAuth");
		}
		return "roleAuthSuccess";
	}
	
	/**
	 * 根据角色获得角色资源关联页面
	 * @return
	 */
	public String getRoleResourseList(){
		return "getRoleResourseList";
	}
	
	/**
	 * 获得所有角色，以JSON方式返回前台
	 * @return
	 * @throws IOException 
	 */
	public String getRoleListJson() throws IOException{
		roleBizBeanList = roleService.getRoleList(null, null);
		log.info("[角色资源]获得所有角色JSON:"+JSONArray.toJSONString(roleBizBeanList));
		response.getWriter().print(JSONArray.toJSONString(roleBizBeanList));
		return null;
	}
	/**
	 * 根据角色id,关联出相应的资源以JSON方式返回前台
	 * @return
	 * @throws IOException
	 */
	public String getRoleMenuJson() throws IOException{
		if(null != roleId ){
			resourseBizBeanList = roleService.getRoleResourse(roleId);
			String html = "";
			if(null != resourseBizBeanList && resourseBizBeanList.size() > 0){
				for (ResourseBizBean vo : resourseBizBeanList) {
					if(null != vo){
						if(null != vo.getChildrenList() && vo.getChildrenList().size() > 0 ){
							html += "{\"id\":\""+vo.getId()+"\",\"pId\":\"0\",\"text\":\""+vo.getTitle()+"\",\"cls\":\"folder\",\"leaf\":false,\"expanded\":false,\"children\":[";
							html += getClidren(vo)+"]},";
						 } else {
							html += "{\"id\":\""+vo.getId()+"\",\"pId\":\"0\",\"text\":\""+vo.getTitle()+"\",\"cls\":\"folder\",\"leaf\": false,\"expanded\":false},";
						 }
					}
				}
				html= "["+html.substring(0, html.length()-1)+"]";
			}
			log.info("[角色资源]根据角色id,关联出相应的资源JSON:"+html);
			response.getWriter().print(html);
		}
		return null;
	}
	/**
	 * 根据角色id,关联出还未分配的资源以JSON方式返回前台
	 * @return
	 */
	public String getNotRoleMenuJson()throws IOException{
		if(null != roleId){
			resourseBizBeanList = roleService.getNotRoleResourse(roleId);
			String html = "";
			if(null != resourseBizBeanList && resourseBizBeanList.size() > 0){
				for (ResourseBizBean vo : resourseBizBeanList) {
					if(null != vo){
						if(null != vo.getChildrenList() && vo.getChildrenList().size() > 0 ){
							html += "{\"id\":\""+vo.getId()+"\",\"pId\":\"0\",\"text\":\""+vo.getTitle()+"\",\"cls\":\"folder\",\"leaf\":false,\"expanded\":false,\"children\":[";
							html += getClidren(vo)+"]},";
						 } else {
							html += "{\"id\":\""+vo.getId()+"\",\"pId\":\"0\",\"text\":\""+vo.getTitle()+"\",\"cls\":\"folder\",\"leaf\": false,\"expanded\":false},";
						 }
					}
				}
				html= "["+html.substring(0, html.length()-1)+"]";
			}
			log.info("[角色资源]根据角色id,关联出还未分配的资源JSON:"+html);
			response.getWriter().print(html);
		}
		return null;
	}
	
	/**
	 * 递归获得子节点的HTML
	 * @param vo
	 * @return
	 */
	private String getClidren(ResourseBizBean vo){
		String html = "";
		for (ResourseBizBean vo1 : vo.getChildrenList()) {
			if(null != vo1){
				if(null != vo1.getChildrenList() && vo1.getChildrenList().size() > 0){
					html += "{\"id\":\""+vo1.getId()+"\",\"pId\":\""+vo1.getParentResourseBizBean().getId()+"\",\"text\":\""+vo1.getTitle()+"\",\"URL\":\""+vo.getUrl()+"\",\"cls\":\"folder\",\"leaf\":false,\"expanded\":true,\"children\":[";
					html += getClidren(vo1)+"]},";
				} else {
					html += "{\"id\":\""+vo1.getId()+"\",\"pId\":\""+vo1.getParentResourseBizBean().getId()+"\",\"text\":\""+vo1.getTitle()+"\",\"checked\":false,\"leaf\":true},";
				}
			}
		}
		return html.substring(0,html.length()-1);
	}
	
	/**
	 * Add Lee 2013-02-20
	 * 增加角色资源
	 * @return
	 */
	public String saveRoleMenu(){
		if(null != roleBizBean){
			roleService.execute(roleBizBean, "saveRoleMenu");
		}
		return null;
	}
	/**
	 * Add Lee 2013-02-21
	 * 删除角色资源
	 * @return
	 */
	public String deleteRoleMenu(){
		if(null != roleBizBean && !StringUtils.isEmpty(roleBizBean.getResourseIds()) && roleBizBean.getId() != null){
			roleService.execute(roleBizBean, "deleteRoleMenu");
		}
		return null;
	}
	
	public void setUsersBizBeanList(List<UsersBizBean> usersBizBeanList) {
		this.usersBizBeanList = usersBizBeanList;
	}

	public List<UsersBizBean> getUsersBizBeanList() {
		return usersBizBeanList;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}

	public Long getRoleId() {
		return roleId;
	}

	public void setUsersBizBean(UsersBizBean usersBizBean) {
		this.usersBizBean = usersBizBean;
	}

	public UsersBizBean getUsersBizBean() {
		return usersBizBean;
	}
	@Resource
	public void setUsersService(UsersService usersService) {
		this.usersService = usersService;
	}

	public UsersService getUsersService() {
		return usersService;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public List<AuthorityBizBean> getAuthList() {
		return authList;
	}

	public void setAuthList(List<AuthorityBizBean> authList) {
		this.authList = authList;
	}

	public AuthService getAuthService() {
		return authService;
	}

	public void setAuthService(AuthService authService) {
		this.authService = authService;
	}

	public AuthorityBizBean getAuthorityBizBean() {
		return authorityBizBean;
	}

	public void setAuthorityBizBean(AuthorityBizBean authorityBizBean) {
		this.authorityBizBean = authorityBizBean;
	}

	public void setResourseBizBeanList(List<ResourseBizBean> resourseBizBeanList) {
		this.resourseBizBeanList = resourseBizBeanList;
	}

	public List<ResourseBizBean> getResourseBizBeanList() {
		return resourseBizBeanList;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public String getIdsStr() {
		return idsStr;
	}

	public void setIdsStr(String idsStr) {
		this.idsStr = idsStr;
	}
}
